// ignore_for_file: public_member_api_docs

import 'dart:io';

import 'package:flutter/material.dart';
import 'package:path_provider_platform_interface/path_provider_platform_interface.dart';
import 'package:pictures_provider_demo/XHFpsMonitor.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Pictures Provider',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Pictures Provider'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  _MyHomePageState(){
    XHFpsMonitor(_refreshUiFps).start();
  }

  final PathProviderPlatform provider = PathProviderPlatform.instance;
  Future<String?>? _externalDownloadsDirectory;
  String uiFps = "0";

  Widget _buildDirectory(
      BuildContext context, AsyncSnapshot<String?> snapshot) {
    Text text = const Text('');
    if (snapshot.connectionState == ConnectionState.done) {
      if (snapshot.hasError) {
        text = Text('Error: ${snapshot.error}');
      } else if (snapshot.hasData) {
        text = Text('path: ${snapshot.data}');
      } else {
        text = const Text('path unavailable');
      }
    }
    return Padding(padding: const EdgeInsets.all(16.0), child: text);
  }

  Widget getGridView(BuildContext context, AsyncSnapshot<String?> snapshot) {
    final List<Widget> list = <Widget>[];
    if (snapshot.connectionState == ConnectionState.done) {
      if (snapshot.hasData) {
        final String combined = snapshot.data!;
        final Directory dir = Directory(combined);
        if (dir.existsSync()) {
          final List<FileSystemEntity> lists = dir.listSync(recursive: false);
          for (final FileSystemEntity entity in lists) {
            if (entity is File) {
              list.add(Image.file(
                entity,
                fit: BoxFit.cover,
                filterQuality: FilterQuality.none,
                width: 100,
                height: 100,
              ));
            }
          }
        }
      }
    }
    return Expanded(
      child: GridView(
        shrinkWrap: true,
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 3,
          childAspectRatio: 1.0,
        ),
        children: list,
      ),
    );
  }

  void _refreshUiFps(fps) {
    setState(() {
      uiFps = fps;
    });
  }

  void _requestDownloadsDirectory() {
    setState(() {
      _externalDownloadsDirectory = provider.getDownloadsPath();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          children: <Widget>[
            Column(
              children: <Widget>[
                Padding(
                  padding: const EdgeInsets.all(10.0),
                  child: ElevatedButton(
                    child: const Text('获取图片'),
                    onPressed: () {
                      _requestDownloadsDirectory();
                    },
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.all(10.0),
                  child: Text('fps: ${uiFps}'),
                ),
              ],
            ),
            FutureBuilder<String?>(
              future: _externalDownloadsDirectory,
              builder: _buildDirectory,
            ),
            FutureBuilder<String?>(
              future: _externalDownloadsDirectory,
              builder: getGridView,
            ),
          ],
        ),
      ),
    );
  }
}
